package cn.wd.web.controller;

import cn.wd.domain.User;
import cn.wd.qo.PageResult;
import cn.wd.qo.QueryObject;
import cn.wd.service.IUserService;
import cn.wd.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/list")
    public JsonResult<PageResult<User>> list(QueryObject qo) {
        PageResult<User> query = userService.query(qo);
        return JsonResult.success(query);
    }

    @RequestMapping("/login")
    public JsonResult<?> login(@RequestBody User user) {
        User newUser = null;
        try {
            newUser = userService.login(user);
        } catch (Exception e) {
            return JsonResult.failed(e.getMessage());
        }
        return JsonResult.success(newUser);
    }

    @RequestMapping("/register")
    public JsonResult<?> register(@RequestBody User user) {
        try {
            userService.register(user);
        } catch (Exception e) {
            return JsonResult.failed(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping("/saveOrUpdate")
    public JsonResult<?> saveOrUpdate(@RequestBody User user) {
        if (user.getId() == null){
            userService.save(user);
        }else {
            userService.update(user);
        }
        return JsonResult.success();
    }

    @RequestMapping("/delete/{id}")
    public JsonResult<?> delete(@PathVariable("id") Long id){
        if (id == null) {
            return JsonResult.failed("id 不能为空!");
        }
        userService.delete(id);
        return JsonResult.success();
    }
}
